package com.xhy.documents_collection.interceptor;

import com.alibaba.fastjson.JSON;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.utils.JwtUtils;
import com.xhy.documents_collection.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author: Xhy
 * CreateTime: 2022-11-25 11:45
 * 拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1. 获取userId
        String uId = JwtUtils.getMemberIdByJwtToken(request);

        // 2.是否存在
        if (ObjectUtils.isEmpty(uId)){
            return response(R.error().message("请登录以后再访问"),response);
        }

        // 放入ThreadLocal
        UserHolder.set(uId);

        return true;

    }

    private boolean response(R r, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSON.toJSONString(r));
        response.getWriter().flush();
        return false;
    }
}
